package com.lottery.ruok.lottrey.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.eventbusObject.ForgetPassword;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.ForgetPasswordRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.SendSMSRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.ForgetPasswordResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.SendSMSResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import utils.Utils;

public class ForgetPasswordActivity3 extends BaseActivity {


    @BindView(R.id.auth_phone)
    EditText authPhone;
    @BindView(R.id.send_auth)
    TextView sendAuth;
    @BindView(R.id.next)
    TextView next;

    private int countTouchAuthButton = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forget_password3);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        init();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void finishSelf(ForgetPassword forgetPassword){
        finish();
    }

    private void init() {
        authPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(authPhone.getText().length() == 0){
                    next.setEnabled(false);
                    next.setTextColor(Color.parseColor("#8539d1"));
                } else {
                    next.setEnabled(true);
                    next.setTextColor(Color.parseColor("#ffffff"));
                }
            }
        });
    }

    @OnClick({R.id.send_auth, R.id.next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.send_auth:
                sendAuths();
                break;
            case R.id.next:
                //sendAnalyticMsg("lottery_" + LoginActivity.ANALYTIC_VERSION + "_me_setting_forgetpwd_sms_next");

                final String phones = getIntent().getStringExtra("phone");// 小韓在 step 1 返回的 "e164String_phone" 格式
                RetrofitBase.getRetrofit().create(ForgetPasswordRequest.class)
                        .getResult(3, phones, null, authPhone.getText().toString(), null)
                        .compose(RxHelper.<ForgetPasswordResponse>handleResult())
                        .subscribe(new RxSubscribe<ForgetPasswordResponse>(this) {
                            @Override
                            protected void _onNext(ForgetPasswordResponse forgetPasswordResponse) {
                                if(forgetPasswordResponse.getStatus() == 1){
                                    Intent intent = new Intent(ForgetPasswordActivity3.this, ForgetPasswordActivity4.class);
                                    intent.putExtra("phone", phones);
                                    startActivity(intent);
                                } else {
                                    Utils.showToast("验证码不正确");
                                }
                            }

                            @Override
                            protected boolean showDialog() {
                                return true;
                            }
                        });
                break;
        }
    }

    private void sendAuths(){
        final int count_time;
        if (countTouchAuthButton == 0) {
            count_time = 60;
        } else {
            count_time = 120;
        }
        countTouchAuthButton++;
        Observable.interval(0, 1, TimeUnit.SECONDS) //0延迟  每隔1秒触发
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())//操作UI主要在UI线程
                .take(count_time + 1) //设置循环次数
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(@NonNull Long aLong) {
                        return count_time - aLong;
                    }
                }) //从60-1
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) {
                        sendAuth.setEnabled(false);
                    }
                }).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(@NonNull Disposable d) {

            }

            @Override
            public void onNext(@NonNull Long aLong) {
                sendAuth.setText(aLong + "");
//                sendAuth.setText("重获(" + aLong + ")");
            }

            @Override
            public void onError(@NonNull Throwable e) {

            }

            @Override
            public void onComplete() {
                sendAuth.setEnabled(true);
                sendAuth.setText("发送");
            }
        });
        RetrofitBase.getRetrofit().create(SendSMSRequest.class).getResult(getIntent().getStringExtra("phone"), "1", getIntent().getStringExtra("e164String"))
                .compose(RxHelper.<SendSMSResponse>handleResult())
                .subscribe(new RxSubscribe<SendSMSResponse>(this) {
                    @Override
                    protected void _onNext(SendSMSResponse sendSMSResponse) {
                        Utils.showToast(sendSMSResponse.getMsg());
                    }

                    @Override
                    protected boolean showDialog() {
                        return true;
                    }
                });
    }
}
